package cn.otrue.patienthealthmanager.fragment;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import android.app.AlertDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import cn.otrue.patienthealthmanager.R;
import cn.otrue.patienthealthmanager.activity.DocterActivitymianfeiwen;
import cn.otrue.patienthealthmanager.activity.HealthPlanActivity;
import cn.otrue.patienthealthmanager.activity.LoginActivity;
import cn.otrue.patienthealthmanager.activity.MainActivity;
import cn.otrue.patienthealthmanager.activity.TiaoJiaBingliActivity;
import cn.otrue.patienthealthmanager.adapter.ImageAdapter;
import cn.otrue.patienthealthmanager.bean.MessageNewsModel;
import cn.otrue.patienthealthmanager.bean.PatientPlanModel;
import cn.otrue.patienthealthmanager.bean.TransferParameter;
import cn.otrue.patienthealthmanager.http.HttpCons;
import cn.otrue.patienthealthmanager.http.HttpServer;
import cn.otrue.patienthealthmanager.http.ServerHandler;
import cn.otrue.patienthealthmanager.utils.CommonUtil;
import cn.otrue.patienthealthmanager.utils.DialogUtil;
import cn.otrue.patienthealthmanager.utils.MyConst;
import cn.otrue.patienthealthmanager.view.CircleFlowIndicator;
import cn.otrue.patienthealthmanager.view.ViewFlow;

import com.google.gson.reflect.TypeToken;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;

/**
 * 首页->首页
 * 
 * @author G
 */
public class MainMainFragment extends BaseFragment implements OnTouchListener {

	private TextView tv_main_main_measurement;
	private TextView tv_main_main_consultation;
	private AlertDialog alertDialog;
	private int mCurrentItem;
	private Runnable runnble;
	private String url;
	private ArrayList<View> items = new ArrayList<View>();
	private List<MessageNewsModel> buyy = new ArrayList<MessageNewsModel>();

	public void ImageSet(String imgurl, ImageView img_headPhoto) {

		DisplayImageOptions options = new DisplayImageOptions.Builder()
				//.showImageOnLoading(R.drawable.iv_user_photo)
				//.showImageOnFail(R.drawable.iv_user_photo)
				.cacheInMemory(true)
				.cacheOnDisk(true).bitmapConfig(Bitmap.Config.RGB_565).build();
		ImageLoader.getInstance().displayImage(imgurl, img_headPhoto, options);
	}

	private Handler Handler = new ServerHandler() {

		@Override
		public void onSuccess(Bundle data, String state, String msg) {

			String dataStr = data.getString(HttpCons.DATA);
			if (state.equals("001")) {
				buyy = HttpServer.gson.fromJson(dataStr,
						new TypeToken<List<MessageNewsModel>>() {
						}.getType());

				for (int i = 0; buyy.size() > i; i++) {
					circleimage(buyy);
				}
				// for (int i = 0; i < buyy.size(); i++) {
				// RadioButton radio = new RadioButton(
				// MainMainFragment.this.getActivity());
				// radio.setButtonDrawable(R.drawable.ofselector_radiobutton);
				// radio.setText(" ");
				// radio.setTag(i);
				// rg_lbt.addView(radio);
				//
				// }
				// initpager();

				// vp_lunbo.setAdapter(new PagerAdapter() {
				//
				// @Override
				// public Object instantiateItem(View container,
				// final int position) {
				// View layout = items.get(position % items.size());
				// vp_lunbo.addView(layout);
				//
				// layout.setOnTouchListener(new OnTouchListener() {
				//
				// private Long btime=0L;
				// private Long etime=0L;
				//
				// @Override
				// public boolean onTouch(View arg0, MotionEvent arg1) {
				//
				// if (arg1.getAction() == MotionEvent.ACTION_DOWN) {
				// btime = System.currentTimeMillis();
				// isDown = true;
				// } else if (arg1.getAction() == MotionEvent.ACTION_UP) {
				// etime = System.currentTimeMillis();
				// isDown = false;
				// if ((etime - btime) <= 500) {
				// Intent intent = new Intent(getActivity(),
				// CenterlunboActivity.class);
				// intent.putExtra("Description",
				// buyy.get(position).getDescription());
				// startActivity(intent);
				// }
				// }
				//
				//
				// return true;
				// }
				// });
				//
				// return layout;
				// }
				//
				// @Override
				// public void destroyItem(View container, int position,
				// Object object) {
				// View layout = items.get(position % items.size());
				// vp_lunbo.removeView(layout);
				// }
				//
				// @Override
				// public boolean isViewFromObject(View arg0, Object arg1) {
				// return arg0 == arg1;
				//
				// }
				//
				// @Override
				// public int getCount() {
				// return items.size();
				// }
				//
				// });

				// vp_lunbo.setOnPageChangeListener(new OnPageChangeListener() {
				//
				// @Override
				// public void onPageSelected(int arg0) {
				// // TODO Auto-generated method stub
				// mCurrentItem = arg0 % buyy.size();
				// vp_lunbo.setCurrentItem(mCurrentItem);
				// for (int i = 0; i < rg_lbt.getChildCount(); i++) {
				// if (mCurrentItem == Integer.parseInt(rg_lbt
				// .getChildAt(i).getTag().toString())) {
				// ((RadioButton) rg_lbt.getChildAt(i))
				// .setChecked(true);
				// }
				// }
				//
				// }

				// @Override
				// public void onPageScrollStateChanged(int arg0) {
				// // TODO Auto-generated method stub
				//
				// }
				//
				// @Override
				// public void onPageScrolled(int arg0, float arg1, int arg2) {
				// // TODO Auto-generated method stub
				//
				// }
				//
				// });

				// runnble = new Runnable() {
				//
				// @Override
				// public void run() {
				// Message msg = new Message();
				// if (!isDown) {
				// if (buyy.size() != 0) {
				//
				// if (mCurrentItem == buyy.size() - 1) {
				//
				// mCurrentItem = 0;
				//
				// } else {
				// mCurrentItem++;
				// }
				// msg.what = mCurrentItem;
				// handlerTime.sendMessage(msg);
				// }
				// }
				// vp_lunbo.postDelayed(runnble, 3000);
				//
				// }
				// };
				// vp_lunbo.postDelayed(runnble, 3000);
				// Toast.makeText(MainMainFragment.this.getActivity(), msg, 0)
				// .show();

			} else {
				Toast.makeText(MainMainFragment.this.getActivity(), msg, 0)
						.show();

			}
		}

		@Override
		public void onFail(Bundle data, String state) {

			if (state.equals(HttpCons.STATE_EXCEPTION)) {
				// 代表进入状态STATE_EXCEPTION 网络异常

			} else if (state.equals(HttpCons.STATE_FORMAT_ERROR)) {
				// 代表进入STATE_FORMAT_ERROR(不是Json)
			} else {
				// 代表进入STATE_ANALYTICAL_ERROR(Json解析错误)

			}
		}
	};

	private Handler getPlanListHandler = new ServerHandler() {

		@Override
		public void onSuccess(Bundle data, String state, String msg) {
			Log.e("http", data.getString("data"));
			if (state.equals(HttpCons.STATE_SUCCESS)) {

				String dataString = data.getString(HttpCons.DATA);
				List<PatientPlanModel> list = HttpServer.gson.fromJson(
						dataString, new TypeToken<List<PatientPlanModel>>() {
						}.getType());
				Intent intent = new Intent();
				intent.setClass(MainMainFragment.this.getActivity(),
						HealthPlanActivity.class);

				if (list != null && list.size() != 0) {
					for (PatientPlanModel patientPlanModel : list) {
						if (patientPlanModel.getDoctorId() != null) {
							if (patientPlanModel.getDoctorId().equals(
									MyConst.getACCOUNT())
									|| patientPlanModel.getDoctorId() == MyConst
											.getACCOUNT()) {
								intent.putExtra("type", MyConst.SHOW_PLAN);
								intent.putExtra("drugplanId",
										patientPlanModel.getDrugplanId());
								intent.putExtra("doctorId",
										MyConst.getACCOUNT());

								break;
							}
						} else {
							Toast.makeText(MainMainFragment.this.getActivity(),
									"本月暂无用药计划", 0).show();
						}
					}
				} else {

					intent.putExtra("type", MyConst.BLANK_PLAN);
					startActivity(intent);
				}

			} else {
				Toast.makeText(MainMainFragment.this.getActivity(), msg, 0)
						.show();
			}
		}

		@Override
		public void onFail(Bundle data, String state) {
			Toast.makeText(MainMainFragment.this.getActivity(), "健康计划" + state,
					Toast.LENGTH_SHORT).show();
		}
	};

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		rootView = inflater.inflate(R.layout.fragment_main_main, null);
		initView(rootView);
		return rootView;
	}

	private void initView(View rootView) {

		viewFlow = (ViewFlow) rootView.findViewById(R.id.viewflow);
		tv_main_main_measurement = (TextView) rootView
				.findViewById(R.id.tv_main_main_measurement);
		tv_main_main_consultation = (TextView) rootView
				.findViewById(R.id.tv_main_main_consultation);
		tv_main_main_measurement.setOnClickListener(this);
		tv_main_main_consultation.setOnClickListener(this);
		// rg_lbt = (RadioGroup) rootView.findViewById(R.id.rg_lbt);
		// vp_lunbo = (ViewPager) rootView.findViewById(R.id.vp_lunbo);

		LinearLayout ll_mian_mian_glucose = (LinearLayout) rootView
				.findViewById(R.id.ll_mian_mian_glucose);
		LinearLayout ll_mian_mian_plan = (LinearLayout) rootView
				.findViewById(R.id.ll_mian_mian_plan);
		LinearLayout ll_mian_mian_drugmanager = (LinearLayout) rootView
				.findViewById(R.id.ll_mian_mian_drugmanager);
		LinearLayout ll_mian_mian_data = (LinearLayout) rootView
				.findViewById(R.id.ll_mian_mian_data);
		LinearLayout ll_mian_mian_doctor = (LinearLayout) rootView
				.findViewById(R.id.ll_mian_mian_doctor);
		LinearLayout ll_mian_mian_community = (LinearLayout) rootView
				.findViewById(R.id.ll_mian_mian_community);

		ll_mian_mian_glucose.setOnClickListener(this);
		ll_mian_mian_plan.setOnClickListener(this);
		ll_mian_mian_drugmanager.setOnClickListener(this);
		ll_mian_mian_data.setOnClickListener(this);
		ll_mian_mian_doctor.setOnClickListener(this);
		ll_mian_mian_community.setOnClickListener(this);
		getLunbo();
	}

	// private Handler handlerTime = new Handler() {
	// @Override
	// public void handleMessage(Message msg) {
	// vp_lunbo.setCurrentItem(msg.what);
	//
	// }
	// };

	void circleimage(List<MessageNewsModel> buyy) {

		viewFlow.setAdapter(new ImageAdapter(buyy, MainMainFragment.this
				.getActivity()));
		viewFlow.setmSideBuffer(buyy.size()); // 实际图片张数，
		// 我的ImageAdapter实际图片张数为3
		CircleFlowIndicator indic = (CircleFlowIndicator) rootView
				.findViewById(R.id.viewflowindic);
		viewFlow.setFlowIndicator(indic);
		viewFlow.setTimeSpan(3000);
		// viewFlow.setSelection(0); // 设置初始位置
		viewFlow.startAutoFlowTimer(); // 启动自动播放
	}

	// private void initpager() {
	// LayoutInflater inflater = LayoutInflater.from(this.getActivity());
	// items.clear();
	// for (int i = 0; i < buyy.size(); i++) {
	// url = buyy.get(i).getImagepath();
	// ImageView view = (ImageView) inflater.inflate(
	// R.layout.item_shouye_lunbo, null);
	// ImageSet(url, view);
	// items.add(view);
	//
	// }
	//
	// }

	// private ViewPager vp_lunbo;
	// private RadioGroup rg_lbt;

	private void getLunbo() {

		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("whichEnd", 0);
		map.put("pageType", MyConst.PAGETYPE_CAROUSEL);

		TransferParameter parameter = new TransferParameter();
		parameter.setUsername("");
		parameter.setPassword("");
		parameter.setData(map);
		new HttpServer().post(HttpCons.querymessageNews, parameter, Handler);
	}

	@Override
	public void onClick(View arg0) {

		if (!CommonUtil.isNetConnectedDialog()) {
			return;
		}

		if (TextUtils.isEmpty(MyConst.getACCOUNT())) {
			View dialogView = initDataInputDialog(new DataDialogListener(), 0);
			if (null != dialogView) {
				alertDialog = DialogUtil.showDialog(this.getActivity(),
						dialogView, true);
				alertDialog.show();
			}
			return;
		}
		switch (arg0.getId()) {
		case R.id.tv_main_main_measurement:
			MainFragment.gotoFragment(0);
			break;
		case R.id.tv_main_main_consultation:
			Intent personinfoIntent = new Intent(getActivity(),
					DocterActivitymianfeiwen.class);
			startActivity(personinfoIntent);
			break;
		case R.id.ll_mian_mian_glucose:
			MainFragment.gotoFragment(0);
			break;
		case R.id.ll_mian_mian_plan:
			MainFragment.gotoFragment(2);
			break;
		case R.id.ll_mian_mian_drugmanager:

			TransferParameter parameter = new TransferParameter();
			parameter.setPagesize("20");
			parameter.setCurrentPage("1");

			parameter.setUsername(MyConst.getACCOUNT());
			HashMap<String, Object> data = new HashMap<String, Object>();
			data.put("patientId", MyConst.getACCOUNT());
			data.put("begintime", CommonUtil.getMinMonthDate(new Date()));
			data.put("endtime", CommonUtil.getMaxMonthDate(new Date()));
			parameter.setData(data);

			new HttpServer().post(HttpCons.QUERY_PATIENT_RUNPLAN, parameter,
					getPlanListHandler);

			break;
		case R.id.ll_mian_mian_data:
			MainFragment.gotoFragment(1);

			break;
		case R.id.ll_mian_mian_doctor:
			((MainActivity) getActivity()).gotoFragment(1);
			break;
		case R.id.ll_mian_mian_community:
			Intent intent = new Intent(getActivity(),
					TiaoJiaBingliActivity.class);
			startActivity(intent);
			break;
		default:
			break;
		}

	}

	private View initDataInputDialog(DataDialogListener dataListener, int i) {
		LayoutInflater inflater = LayoutInflater.from(this.getActivity());
		View view = inflater.inflate(R.layout.dialog_input_daaa, null);
		TextView tv_catt_dialogLeft = (TextView) view
				.findViewById(R.id.tv_catt_dialogLeft);
		tv_catt_dialogLeft.setOnClickListener(dataListener);
		TextView tv_catt_dialogRight = (TextView) view
				.findViewById(R.id.tv_catt_dialogRight);
		tv_catt_dialogRight.setOnClickListener(dataListener);
		return view;

	}

	private boolean isDown = false;
	private View rootView;
	private ViewFlow viewFlow;

	@Override
	public boolean onTouch(View arg0, MotionEvent arg1) {
		if (arg1.getAction() == MotionEvent.ACTION_DOWN) {
			isDown = true;
		} else if (arg1.getAction() == MotionEvent.ACTION_UP) {
			isDown = false;
		}

		return true;
	}

	public static Fragment newInstance() {
		return new MainMainFragment();
	}

	@Override
	public String setPageName() {
		// TODO Auto-generated method stub
		return null;
	}

	public class DataDialogListener implements OnClickListener {

		@Override
		public void onClick(View v) {

			switch (v.getId()) {
			case R.id.tv_catt_dialogLeft:// 取消
				alertDialog.dismiss();
				break;
			case R.id.tv_catt_dialogRight:// 确定

				Intent personinfoIntent = new Intent(getActivity(),
						LoginActivity.class);
				startActivity(personinfoIntent);
				alertDialog.dismiss();
			}
		}

	}

}
